const paramTypeMap = {
  '0': 'string',
  '1': 'File',
  '2': 'string', // json
  '3': 'number', // int
  '4': 'number', // float
  '5': 'number', // double
  '6': 'string', // date
  '7': 'string', // datetime
  '8': 'boolean', // boolean
  '9': 'string', // byte
  '10': 'number', // short
  '11': 'number', // long
  '12': 'string[]', // array
  '13': 'Record&#60string, any&#62', // object
  '14': 'number', // number
  '15': 'null', // null
  'char': 'string', // char
}

const interfaceType = {
  '12': true,
  '13': true,
}



// 行hmtl
const lineHtml = ({ attribute: attr, interfaceKey, isRequest }) => {

  const optionalSymbol = (isRequest && attr.paramNotNull === '1') ? '<span class="optional-symbol">?</span>' : '';
  const commentStr = attr.paramName ? `<span class="comment">&nbsp;&nbsp;&nbsp;&nbsp;// ${attr.paramName}</span>` : '';
  return `
  &nbsp;&nbsp;&nbsp;&nbsp;
  <span class="key">${attr.paramKey}${optionalSymbol}</span>: 
  <span class="keyword">${interfaceKey ? interfaceKey : paramTypeMap[attr.paramType]}</span>;
  ${commentStr}
  <br />`
}

// 对属性进行html格式化
const tranformToHtml = ({ attributes, isRequest = false, interfaceName }) => {
  try {
    let interfaceNameStr = interfaceName ? `<span class='keyword'> interface</span> ${interfaceName} ` : '';
    let html = `<p>${interfaceNameStr}<span class="brackets">{</span><br/>`;

    attributes.forEach(attr => {
      if (interfaceType[attr.paramType] && attr.childList?.length) {
        const subInterfaceName = attr.paramKey.replace(/^\w/, (v) => v.toUpperCase());
        html = tranformToHtml({
          attributes: attr.childList,
          isRequest,
          interfaceName: subInterfaceName,
        }) + html;
        return html += lineHtml({ attribute: attr, interfaceKey: subInterfaceName + (attr.paramType === '12' ? '[]' : ''), isRequest });
      }
      html += lineHtml({ attribute: attr, isRequest });
    })

    return html += '<span class="brackets">}</span></p>'
  } catch (err) {
    return `
    解析可能发生的错误，可点击最下方的显示原始数据，然后复制，发送到作者邮箱(q473658336@163.com)或者在gitlab提issue进行反馈。
    ${err}`
  }
}

const apiPath2InterfaceName = (str) => {
  if (!str) return '';
  let pathArr = str.split('/');
  pathArr = pathArr.map((path) => path.replace(/[\{\}]/, "").replace(/\W/, '').replace(/^\w/, (v) => v.toUpperCase()))
  return pathArr.join('');
}



const apiNameDom = document.getElementById('apiName');
const queryParamsDom = document.getElementById('queryParams');
const backDatasDom = document.getElementById('backDatas');
const restParamsDom = document.getElementById('restParams');
const showRawApiDataBtn = document.getElementById('showRawApiData');
const rowApiDataDisplayDom = document.getElementById('row-api-data');
const rowApiDataContentDom = document.getElementById('row-api-data-content');
const copyBtn = document.getElementById('copy');


function pageResultInit() {
  apiNameDom.innerHTML = '';
  queryParamsDom.innerHTML = '';
  backDatasDom.innerHTML = '';
  restParamsDom.innerHTML = '';
  rowApiDataContentDom.value = '';
  copyBtn.innerText = '复制';
  rowApiDataDisplayDom.classList.remove('show')
  document.body.classList.add('show-tips')
}

showRawApiDataBtn.addEventListener('click', () => {
  rowApiDataDisplayDom.classList.add('show')
})
copyBtn.addEventListener('click', () => {
  try {
    rowApiDataContentDom.select();
    document.execCommand("copy");
    copyBtn.innerText = '应该复制成功了，没成功就手动复制吧[狗头]';

  } catch (err) {
    copyBtn.innerText = '应该复制失败了，手动复制下吧[狗头]';
  }
})



// 属性列表递归
function paramsListRecursion(list, dataStructureList) {
  let arr = [];
  list.forEach(item => {
    if (item.structureID) {
      return arr.push(...(dataStructureList?.[item.structureID]?.structureData || []))
    }
    if (item.childList && item.childList.length) {
      item.childList = paramsListRecursion(item.childList, dataStructureList);
    }
    arr.push(item)
  })
  return arr;
}

function doTransform(datasObj) {

  let { apiInfo: { baseInfo, requestInfo, resultInfo, dataStructureList, urlParam, restfulParam } } = datasObj;


  // 显示api名称和路径
  apiNameDom.innerHTML = `${baseInfo.apiName}(${baseInfo.apiURI})`;


  if (requestInfo && requestInfo.length) {
    let attributes = paramsListRecursion(requestInfo, dataStructureList);
    queryParamsDom.innerHTML = attributes && attributes.length ? tranformToHtml({
      interfaceName: apiPath2InterfaceName(baseInfo.apiURI) + 'QueryParams',
      attributes,
      isRequest: true
    }) : '这个请求他没有入参';
  }

  if (resultInfo && resultInfo.length) {
    let attributes = paramsListRecursion(resultInfo[0].paramList, dataStructureList);
    backDatasDom.innerHTML = attributes && attributes.length ? tranformToHtml({
      interfaceName: apiPath2InterfaceName(baseInfo.apiURI) + 'BackData',
      attributes,
    }) : '这个请求他没有出参';

  }

  // get请求的url入参需要单独解析
  if (baseInfo.apiRequestType === 1) {
    queryParamsDom.innerHTML = urlParam && urlParam.length ? tranformToHtml({
      interfaceName: apiPath2InterfaceName(baseInfo.apiURI) + 'QueryParams',
      attributes: paramsListRecursion(urlParam, dataStructureList),
      isRequest: true
    }) : '这个请求他没有入参';
  }

  if (restfulParam && restfulParam.length) {
    restParamsDom.innerHTML = tranformToHtml({
      interfaceName: 'RestfulParam',
      attributes: paramsListRecursion(restfulParam, dataStructureList),
      isRequest: true
    })
    if (queryParamsDom.innerHTML === '这个请求他没有入参') queryParamsDom.innerHTML = '';
  }


}


window.addEventListener('message', (event) => {
  if (event.data === 'init') {
    pageResultInit();
    return true;
  }
  if (!event.data) return false;
  pageResultInit();
  rowApiDataContentDom.value = event.data;
  document.body.classList.remove('show-tips');
  doTransform(JSON.parse(event.data));
})




